import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:yt_devops/components/app_permission/permission_widget.dart';
import 'package:yt_devops/components/brn/brn_bottom_button_panel.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/components/yt_text_style.dart';
import 'package:yt_devops/pages/site/site_setting/siet_elec_price_setting/add_mains_electricity_price/views/effective_data_widget.dart';
import 'package:yt_devops/pages/site/site_setting/siet_elec_price_setting/add_mains_electricity_price/views/effective_date_widgets.dart';
import 'package:yt_devops/pages/site/site_setting/siet_elec_price_setting/add_mains_electricity_price/views/item_tow_checkbox_widget.dart';
import 'package:yt_devops/pages/site/site_setting/siet_elec_price_setting/add_photovoltaic_price_set/views/photoVoltaic_stage_price_widget.dart';
import 'package:yt_devops/pages/site/site_setting/siet_elec_price_setting/add_photovoltaic_price_set/views/photovoltaic_stage_price_widgets.dart';
import 'package:yt_devops/pages/site/site_setting/siet_elec_price_setting/elec_price_title_widget.dart';
import 'package:yt_devops/pages/site/site_setting/siet_elec_price_setting/site_elec_price_setting_model.dart';
import 'package:yt_devops/pages/site/site_setting/siet_elec_price_setting/site_internet_elec_detail/site_internet_elec_detail_controller.dart';
import 'package:yt_devops/pages/site/site_setting/site_setting_base_info/widgets/item_widget.dart';
import 'package:yt_devops/resources/resources.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/utils/constants/permission_page_constant.dart';

import '../../../../../components/app_bar/app_bar_widget.dart';

class SiteInternetElecDetailView extends GetView<SiteInternetElecDetailController> {
  SiteInternetElecDetailView({Key? key}) : super(key: key);

  @override
  final controller = Get.put(SiteInternetElecDetailController());

  @override
  Widget build(BuildContext context) {
    GetStorage storage = GetStorage();
    String monetaryUnitName = storage.read('monetaryUnitName')??'元';
    if(monetaryUnitName == '元' || monetaryUnitName == '¥'){
      monetaryUnitName = ResKey.yuan.tr;
    }

    return GetBuilder<SiteInternetElecDetailController>(
      init: controller,
      builder: (controller) {
        return Scaffold(
          resizeToAvoidBottomInset: true,
          backgroundColor: Colour.backgroundColor,
          appBar: AppBarWidget.withRightActions(
            ResKey.detailsOfGridElePrices.tr,
            actions: [
          PermissionWidget(permissionStringList: const [PermissionConstant.homeSiteManageSettingElectricitySettingPvEdit],
            child:Visibility(
                visible: !controller.isEnableEdit,
                child: IconButton(
                  icon:
                  Image.asset(ImageAssets.siteSettingBaseInfoEdit),
                  onPressed: controller.edit,
                ),
              ))
            ],
          ),

          body: controller.isEnableEdit?Container(
              // color: Colour.white,
              child:ListView(padding: EdgeInsets.zero, children: [
                      Container(
                        height: 10,
                        color: Colour.backgroundColor,
                      ),
              Container(
                  clipBehavior: Clip.hardEdge,
                  margin: const EdgeInsets.only(left: 16,right: 16),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8),
                    color: Colors.white,
                  ),
                  child:Column(
                      children: [ElecPriceTitleWidget(controller.titleStringList[0]),
                      ItemWidget(
                        ResKey.siteSettingElectricityRoleName.tr,
                        controller.ruleNameController,
                        unitString: '',
                        titleColor: Colour.otherTextColor,
                        inputTextColor: Colour.mainTextColor,
                        titleFont: 14,
                        isCanEdit:true,
                        textChangeCallBack: (str){
                          controller.checkCommitStatus();
                        },
                      ),
                      ItemTowCheckboxWidget(ResKey.siteSettingElectricityEffectiveStatus.tr, ResKey.siteSettingEffective.tr, ResKey.siteSettingUnEffective.tr, controller.status, (index) {
                        Log.d('index=' + index.toString());
                        controller.status = index;
                      })])),
                      Container(
                        height: 10,
                        color: Colour.backgroundColor,
                      ),
                      EffectiveDateWidgets(controller.timeDateList, (){
                        controller.updateTimeList();
                      }, (index){
                        controller.deleteTimeList(index);
                      },(){
                        controller.update();
                      }),

                      Container(
                        height: 10,
                        color: Colour.backgroundColor,
                      ),
                      PhotoStagePriceWidgets(controller.stagePriceList, (){
                        controller.updateStagePriceList();
                      }, (index){
                        controller.deleteStagePriceList(index);
                      }, (){
                        controller.update();
                      },(){
                        controller.update();
                      }),
                      Container(
                        height: 10,
                        color: Colour.backgroundColor,
                      ),
              ])):ListView(
            children: [
              Container(
                margin: EdgeInsets.only(bottom: 10, top: 10),
                color: Colour.backgroundColor,
                child: Column(
                  children: [
                    Container(
                      height: 160,
                      clipBehavior: Clip.hardEdge,
                      margin: const EdgeInsets.only(left: 16,right: 16),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(8),
                        color: Colors.white,
                      ),
                      child: GetBuilder<SiteInternetElecDetailController>(
                          builder: (controller) {
                            List<InfoModel> basicList = [
                              InfoModel(ResKey.basicInfo.tr, ''),
                              InfoModel(
                                  ResKey.siteSettingElectricityRoleName.tr, controller.model.name.toString()),
                              InfoModel(
                                  ResKey.siteSettingElectricityEffectiveStatus.tr, controller.model.status == 0
                                  ? ResKey.siteSettingUnEffective .tr
                                  : ResKey.siteSettingEffective.tr),
                            ];
                            return listWidget(count: 3, items: basicList!);
                          }),
                    ),
                    Container(
                      clipBehavior: Clip.hardEdge,
                      margin: const EdgeInsets.only(left: 16,right: 16,top: 10),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(8),
                        color: Colors.white,
                      ),

                      child: GetBuilder<SiteInternetElecDetailController>(
                          builder: (controller) {
                            List<InfoModel> basicList = [];
                            if (controller.model.effectiveTimeList != null) {
                              for (int i = 0;
                              i < controller.model.effectiveTimeList!.length;
                              i++) {
                                EffectiveTimeList time =
                                controller.model.effectiveTimeList![i];
                                basicList.add(InfoModel('${ResKey.siteSettingDate.tr}${i + 1}',
                                    '${time.effectiveTime} - ${time
                                        .expirationTime}'));
                              }
                            }
                            basicList.insert(0, InfoModel(ResKey.siteSettingEffectiveDate.tr, ''));
                            return listWidget(
                                count: basicList.length, items: basicList);
                          }),
                    ),
                    Container(
                      clipBehavior: Clip.hardEdge,
                      margin: const EdgeInsets.only(left: 16,right: 16,top: 10),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(8),
                        color: Colors.white,
                      ),
                      child: GetBuilder<SiteInternetElecDetailController>(
                          builder: (controller) {
                            List<PeriodTime> basicList = [];
                            if (controller.model.hoursPriceList != null) {
                              for (int i = 0;
                              i < controller.model.hoursPriceList!.length;
                              i++) {
                                HoursPriceList time =
                                controller.model.hoursPriceList![i];
                                basicList.add(PeriodTime(
                                    ResKey.siteSettingElectricityTimeStage.tr + (i+1).toString(),
                                    '${time.intervalStartTime} - ${time
                                        .intervalEndTime}',
                                    ResKey.siteSettingElectricityElectrovalency.tr,
                                    '${time.electricityFees}$monetaryUnitName/kWh'));
                              }
                            }
                            basicList.insert(
                              0,
                              PeriodTime(ResKey.siteSettingElectricityStagePrice.tr, '', '', ''),
                            );
                            return periodTimeListWidget(
                                count: basicList.length, items: basicList);
                          }),
                    ),
                  ],
                ),
              ),
            ],
          ),
          bottomNavigationBar: controller.isEnableEdit?Container(
            color: Colour.white,
            padding: EdgeInsets.only(bottom: ScreenUtil().bottomBarHeight),
            child: YtBrnBottomButtonPanel(
                enableMainButton: controller.isEnableCommit,
                mainButtonName: ResKey.save.tr,
                mainButtonOnTap: () => controller.save(),
                secondaryButtonName: ResKey.cancel.tr,
                enableSecondaryButton: true,
                secondaryButtonBorder:
                Border.all(color: Colour.dividerColor),
                secondaryButtonOnTap: () => controller.cancelEdit()),
          ):null,
        );
      },
    );
  }

  Widget periodTimeListWidget({int? count, List<PeriodTime>? items}) {
    return ListView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      itemCount: count,
      itemBuilder: (BuildContext context, int index) {
        if (items != null && items.isNotEmpty) {
          if (index == 0) {
            return Column(
              children: [
                titleWidget(items[index].timeName),
                Divider(height: 1
                    , color: Colour.dividerColor),
              ],
            );
          } else if (index == count! - 1) {
            return Column(
              children: [
                periodTimeWidget(
                    items[index].timeName,
                    items[index].timeContent,
                    items[index].elecName,
                    items[index].elecContent),
              ],
            );
          } else {
            return Column(
              children: [
                periodTimeWidget(
                    items[index].timeName,
                    items[index].timeContent,
                    items[index].elecName,
                    items[index].elecContent),
                const Divider(
                  color: Colour.dividerColor,
                  height: 1,
                  indent: 16,
                  endIndent: 0,
                ),
              ],
            );
          }
        }
        return Container(); // 返回一个空的Widget
      },
    );
  }

  Widget periodTimeWidget(String leftTimeName, String rightTimeContent,
      String leftElecTypeName, String rightElecTypeContent,
      {int textHeight = 80}) {
    return Container(
      height: textHeight
          .toDouble(),
      padding: EdgeInsets.only(
          left: 16.w, right: 16.w, top: 16, bottom: 16),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                leftTimeName,
                style: TextStyles.styleWith(
                  14.sp,
                  color: Colour.otherTextColor,
                ),
              ),
              Text(
                rightTimeContent,
                style: TextStyles.styleWith(
                  14.sp,
                  color: Colour.mainTextColor,
                ),
              ),
            ],
          ),
          SizedBox(height: 4,),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                leftElecTypeName,
                style: TextStyles.styleWith(
                  14.sp,
                  color: Colour.otherTextColor,
                ),
              ),
              Text(
                rightElecTypeContent,
                style: TextStyles.styleWith(
                  14.sp,
                  color: Colour.mainTextColor,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget listWidget({int? count, List<InfoModel>? items}) {
    return ListView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      itemCount: count,
      itemBuilder: (BuildContext context, int index) {
        if (items != null && items.isNotEmpty) {
          if (index == 0) {
            return Column(
              children: [
                titleWidget(items[index].name),
                Divider(height: 1, color: Colour.dividerColor),
              ],
            );
          } else if (index == count! - 1) {
            return Column(
              children: [
                infoWidget(items[index].name, items[index].content),
              ],
            );
          } else {
            return Column(
              children: [
                infoWidget(items[index].name, items[index].content),
                const Divider(
                  color: Colour.dividerColor,
                  height: 1,
                  indent: 16,
                  endIndent: 0,
                ),
              ],
            );
          }
        }
        return Container(); // 返回一个空的Widget
      },
    );
  }

  Widget infoWidget(String leftText, String rightText, {int textHeight = 50}) {
    return Container(
      height: textHeight
          .toDouble(),
      padding: EdgeInsets.only(left: 16.w, right: 16.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            leftText,
            style: TextStyles.styleWith(
              14.sp,
              color: Colour.otherTextColor,
            ),
          ),
          Text(
            rightText,
            style: TextStyles.styleWith(
              14.sp,
              color: Colour.mainTextColor,
            ),
          ),
        ],
      ),
    );
  }

  Widget titleWidget(String titleText) {
    return Container(
      height: 50,
      padding: EdgeInsets.only(
        left: 16.w,
      ),
      alignment: Alignment.centerLeft,
      child: Text(
        titleText,
        softWrap: true,
        style: TextStyles
            .styleWith(
          18.sp,
          color: Colour.mainTextColor,
        )
            .mediumStyle,
      ),
    );
  }

  _addEffectiveDataWidgets(BuildContext context){
    List<Widget> list = [];
    if(controller.timeDateList.length > 1){
      for(int i =1;i<controller.timeDateList.length;i++){
        var widget =  EffectiveDataWidget(context,'${ResKey.siteSettingDate.tr}${i+ 1}',
          controller.timeDateList[i]['effectiveTime'],
          controller.timeDateList[i]['expirationTime'],(startDateTime,endDateTime){
            controller.timeDateList[i] = {
              'effectiveTime':startDateTime,
              'expirationTime':endDateTime,

            };
            controller.update();
          },(){
            controller.deleteTimeList(i);
          },isDelete: true,);
        list.add(widget);
      }
    }
    return SizedBox(
      height: (controller.timeDateList.length -1) * 55,
      child: Column(
        children: list,
      ),
    );
  }
  _addStagePriceWidgets(BuildContext context) {
    List<Widget> list = [];
    if (controller.stagePriceList.length > 1) {
      for (int i = 1; i < controller.stagePriceList.length; i++) {
        var widget = PhotoVoltaicWidget(
          context,
          ResKey.siteSettingElectricityTimeStage.tr,
          controller.stagePriceList[i]['intervalStartTime'],
          controller.stagePriceList[i]['intervalEndTime'],
          controller.stagePriceList[i]['electricityFees'].toString(),
              (startDateTime, endDateTime) {
            String price =
            controller.stagePriceList[0]['electricityFees'].toString();
            controller.stagePriceList[0] = {
              'intervalStartTime': startDateTime,
              'intervalEndTime': endDateTime,
              'electricityFees': price
            };
            controller.update();
          },
              () {
            controller.deleteStagePriceList(i);
          },
              (str) {
            var map = controller.stagePriceList[i];
            map['electricityFees'] = str;
            controller.stagePriceList[i] = map;
          },isDelete: true,);
        list.add(widget);
      }
    }
    return SizedBox(
      height: (controller.stagePriceList.length - 1) * 110,
      child: Column(
        children: list,
      ),
    );
  }

}

class InfoModel {
  String name;
  String content;

  InfoModel(this.name, this.content);
}

class PeriodTime {
  // 时间段
  String timeName;
  String timeContent;

  // 电价类型
  String elecName;
  String elecContent;

  PeriodTime(this.timeName, this.timeContent, this.elecName,
      this.elecContent);
}
